import wx
from decimal import Decimal as Dec
import decimal
import sys
import copy

from DataTool import DataTool
from QuotaReader import QuotaReader
from SqlDict import SqlDict
# from MyListCtrl import EditableListCtrl

class DiaTable3Change(wx.Dialog):

    TableANames = ['序号', '定额编号', '定额名称', '单位', '普工定额', '技工定额', '普通费率', '拆除费率1', '拆除费率2', '取值说明',]
    TableBNames = ['是否关联', '定额名称', '单位', '仪器仪表/机械', '台班', '单价',]

    ColWidth = [45, 70, 300, 45, 60, 60, 80, 80, 80, 200]
    ColBWidth = [70, 300, 80, 200, 80, 80]

    TableA2Change = [0, 1, 2, 4, 5, -1, -2, -3, 10]
    TableB2Change = [12, 1, 2, 4, 5, 6]

    def __init__(self, parent, title, *args, **kwargs):
        # kwargs 中 datas 为 [[redict, rowdict, teardict], ...]
        self.datas = kwargs.get('datas', [])
        self.indexA, self.indexB, self.indexC = -1, -1, -1
        super().__init__(parent, -1, title)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
        # 表三甲
        addquota = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, name='添加定额', size=(1000,300))
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectedA, addquota)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnChangeDatas, addquota)

        mainsizer.Add(addquota, 0, flag=wx.ALL|wx.EXPAND, border=5)
        # 机械 仪器仪表列
        nb = wx.Notebook(self,style=wx.NB_TOP|wx.NB_FIXEDWIDTH)
        nbnamelist = ['机械', '仪器仪表', '材料']
        
        for index, name in enumerate(nbnamelist):
            listctrl = wx.ListCtrl(nb, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, name=name)
            nb.AddPage(listctrl, name)
            self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnCheckRelated, listctrl)
            self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnClickTable, listctrl)
        mainsizer.Add(nb, 0, flag=wx.ALL|wx.EXPAND, border=5)

        btnsave = wx.Button(self, -1, "保存(&S)")
        btncal = wx.Button(self, -1, "取消(&C)")
        btntest = wx.Button(self, -1, "TEST(&C)")
        self.Bind(wx.EVT_BUTTON, self.OnSave, btnsave)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, btncal)
        self.Bind(wx.EVT_BUTTON, self.PrintData, btntest)
        mainsizer.Add(btnsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        btnsizer.Add((140,20), 1)
        btnsizer.Add(btnsave,0)
        btnsizer.Add((140,20), 0)
        btnsizer.Add(btncal)
        btnsizer.Add((140,20), 1)
        btnsizer.Add(btntest)

        self.InitListCtrl()
        self.InitImage()

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)

    def PrintData(self, event):
        print(self.datas)

    def OnChangeDatas(self, event):
        obj = event.GetEventObject()
        selected = obj.GetFirstSelected()
        data = self.GetRowData(selected)
        dia = ChangeData(self, '修改定额数据', data=data)
        data = dia.ShowModal()
        if data != 5101:
            self.SetRowData(selected, data)
        dia.Destroy()
        self.InitListCtrl()

    def GetRowData(self, rownum):
        ExportData = []
        temp = []
        for j in self.TableA2Change[1:]:
            if j < 0:
                temp.append(self.datas[rownum][2][-j-1])
            else:
                temp.append(self.datas[rownum][0]['表三甲'][0][j])
        ExportData.append(temp)

        temp = []
        for i in ['表三乙', '表三丙']:
            if len(self.datas[rownum][0][i]) > 0:
                for k in self.datas[rownum][0][i]:
                    temp1 = []
                    for j in self.TableB2Change[1:]:
                        temp1.append(k[j])
                    temp.append(temp1)
            ExportData.append(temp)
            temp = []
        return ExportData
    
    def SetRowData(self, rownum, data):
        for index, j in enumerate(self.TableA2Change[1:]):
            if j < 0:
                self.datas[rownum][2][-j-1] = data[0][index]
            else:
                self.datas[rownum][0]['表三甲'][0][j] = data[0][index]
        
        for index, i in enumerate(['表三乙', '表三丙']):
            if len(self.datas[rownum][0][i]) > 0:
                for index2, k in enumerate(self.datas[rownum][0][i]):
                    for index3, j in enumerate(self.TableB2Change[1:]):
                        k[j] = data[index + 1][index2][index3]
        
        self.InitListCtrl()

    def OnSave(self, event):
        self.EndModal(retCode=1)

    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.datas
        else:
            return 5101

    def OnSelectedA(self, event):
        obj = self.thistable = event.GetEventObject()
        obj.flag = True
        index = event.GetIndex()
        self.indexA = index
        namelist = ['机械', '仪器仪表']
        tablenamelist = ['表三乙', '表三丙']
        for nameidex, name in enumerate(namelist):
            listctrl = self.FindWindowByName(name)
            listctrl.DeleteAllItems()
            datas = self.datas[index][0][tablenamelist[nameidex]]

            for row, data in enumerate(datas):
                i = listctrl.InsertItem(row, '')
                if data[12] == '0':
                    listctrl.SetItemImage(row, 0)
                else:
                    listctrl.SetItemImage(row, 1)
                for col, ocol in enumerate(self.TableB2Change[1:]):
                    listctrl.SetItem(i, col+1, str(data[ocol]))
        

    def OnCheckRelated(self, event):
        index = event.GetIndex()
        obj = event.GetEventObject()
        obj.flag = True
        name = obj.GetName()
        img_idx = event.GetImage()
        if name == '机械':
            tablename = '表三乙'
        else:
            tablename = '表三丙'
        if img_idx == 1:
            obj.SetItemImage(index, 0)
            self.datas[self.indexA][0][tablename][index][12] = '0'
        elif img_idx == 0:
            obj.SetItemImage(index, 1)
            self.datas[self.indexA][0][tablename][index][12] = '1'

    def OnClickTable(self, event):
        self.thistable = event.GetEventObject()
        obj = event.GetEventObject()
        index = event.GetIndex()
        name = obj.GetName()
        self.DisSelectOther(name)
        if name == '机械':
            self.indexB = index
            self.FindWindowByName(name).flag = True
        elif name == '仪器仪表':
            self.indexC = index
            self.FindWindowByName(name).flag = True
        else:
            pass
        self.DisSelectOther(name)
        # event.Skip()

    def DisSelectOther(self, name=None):
        namelist = ['添加定额', '机械', '仪器仪表']
        indexlist = [self.indexA, self.indexB, self.indexC]
        if name is not None:
            try:
                indexlist.pop(namelist.index(name))
                namelist.remove(name)
            except ValueError:
                pass
        for index, name in enumerate(namelist):
            obj = self.FindWindowByName(name)
            obj.Select(-1, 0)
            obj.flag = False

    def InitListCtrl(self):
        namelist = ['添加定额', '机械', '仪器仪表']
        for name in namelist:
            listctrl = self.FindWindowByName(name)
            listctrl.ClearAll()
            if name == '添加定额':
                thistablenames = self.TableANames
                thiscolwidth = self.ColWidth
            else:
                thistablenames = self.TableBNames
                thiscolwidth = self.ColBWidth
            # 初始化标签行
            for col, name in enumerate(thistablenames):
                listctrl.InsertColumn(col, name)
                listctrl.SetColumnWidth(col, thiscolwidth[col])
        # 初始化数据
        listctrl = self.FindWindowByName('添加定额')
        listctrl.UnEditCols = [0, 1]
        for row, value in enumerate(self.datas):
            # serial = value[0]['表三甲'][0][0]
            # idnum = value[0]['表三甲'][0][11]
            tear = value[2]
            index = listctrl.InsertItem(row, str(row + 1))
            for col, data in enumerate(self.TableA2Change):
                if data < 0:
                    listctrl.SetItem(index, col+1, str(tear[(-data) - 1]))
                else:
                    listctrl.SetItem(index, col+1, str(value[0]['表三甲'][0][data]))
        
        listctrl.Select(0)
        self.DisSelectOther()

    def InitImage(self):
        
        imgsz = (16, 16)
        check_image = self.CreateBitmap(wx.CONTROL_CHECKED, imgsz)
        uncheck_image = self.CreateBitmap(0, imgsz)

        mech = self.FindWindowByName('机械')
        meter = self.FindWindowByName('仪器仪表')
        mater = self.FindWindowByName('材料')
        for i in [mech, meter, mater]:
            i.imagelist = wx.ImageList(*imgsz)
            i.imagelist.Add(uncheck_image)
            i.imagelist.Add(check_image)
            i.AssignImageList(i.imagelist, wx.IMAGE_LIST_SMALL)

        self.__last_check_ = None

    def CreateBitmap(self, flag=0, size=(16, 16)):
        """Create a bitmap of the platforms native checkbox. The flag
        is used to determine the checkboxes state (see wx.CONTROL_*)

        """
        bmp = wx.Bitmap(*size)
        dc = wx.MemoryDC(bmp)
        dc.SetBackground(wx.WHITE_BRUSH)
        dc.Clear()
        wx.RendererNative.Get().DrawCheckBox(self, dc,
                                             (0, 0, size[0], size[1]), flag)
        dc.SelectObject(wx.NullBitmap)
        return bmp
    

class ChangeData(wx.Dialog):
    TableANames = ['定额名称', '单位', '普工定额', '技工定额', '普通费率', '拆除费率1', '拆除费率2', '取值说明',]
    TableBNames = ['仪器仪表/机械', '台班', '单价',]

    ColWidth = [300, 45, 60, 60, 80, 80, 80, 200]
    ColBWidth = [200, 130, 130]

    Names = ['表三甲', '表三乙', '表三丙',]

    def __init__(self, parent, title, *args, **kwargs):
    # kwargs 中 datas 为 [[redict, rowdict, teardict], ...]
        super().__init__(parent, -1, title)
        self.data = kwargs.get('data', [])
        MainSizer = wx.BoxSizer(wx.VERTICAL)
        SecSizer = wx.BoxSizer(wx.HORIZONTAL)
        BtnSizer = wx.BoxSizer(wx.HORIZONTAL)
        Asizer = wx.StaticBoxSizer(wx.VERTICAL, self, '表三甲')
        ASecsizer = wx.BoxSizer(wx.HORIZONTAL)
        Bsizer = wx.StaticBoxSizer(wx.VERTICAL, self, '表三乙')
        BSecsizer = wx.BoxSizer(wx.HORIZONTAL)
        Csizer = wx.StaticBoxSizer(wx.VERTICAL, self, '表三丙')
        CSecsizer = wx.BoxSizer(wx.HORIZONTAL)

        for index, name in enumerate(self.TableANames):
            text = wx.StaticText(self, -1, name, size=(self.ColWidth[index], -1))
            ASecsizer.Add(text, 0, wx.EXPAND|wx.ALL, 5)
        for sizer in [BSecsizer, CSecsizer]:
            for index, name in enumerate(self.TableBNames):
                text = wx.StaticText(self, -1, name, size=(self.ColBWidth[index], -1))
                sizer.Add(text, 0, wx.EXPAND|wx.ALL, 5)

        Asizer.Add(ASecsizer)
        Bsizer.Add(BSecsizer)
        Csizer.Add(CSecsizer)

        MainSizer.Add(Asizer, 0, wx.EXPAND|wx.ALL, 5)
        MainSizer.Add(SecSizer)
        SecSizer.Add(Bsizer, 1, wx.EXPAND|wx.ALL, 5)
        SecSizer.Add(Csizer, 1, wx.EXPAND|wx.ALL, 5)
        MainSizer.Add(BtnSizer, 1, wx.EXPAND|wx.ALL, 5)

        BtnSave = wx.Button(self, -1, "保存(&S)")
        BtnCal = wx.Button(self, -1, "取消(&C)")
        self.Bind(wx.EVT_BUTTON, self.OnSave, BtnSave)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, BtnCal)
        BtnSizer.Add((140,20), 1)
        BtnSizer.Add(BtnSave,0)
        BtnSizer.Add((140,20), 0)
        BtnSizer.Add(BtnCal)
        BtnSizer.Add((140,20), 1)

        self.InitData([Asizer, Bsizer, Csizer])

        self.SetSizer(MainSizer)
        MainSizer.Fit(self)
        MainSizer.SetSizeHints(self)

    def InitData(self, sizers):
        for index, d in enumerate(self.data):

            sizer = wx.BoxSizer(wx.HORIZONTAL)
            if index == 0:
                names = self.TableANames
                width = self.ColWidth
                start = 0
            else:
                names = self.TableBNames
                width = self.ColBWidth
                start = 2
            
            if len(d) != 0:
                if not isinstance(d[0], list):
                    for index2, v in enumerate(d[start:]):
                        t = wx.TextCtrl(self, -1, str(v), size=(width[index2], -1), name=names[index2]+str(index))
                        sizer.Add(t, 0, wx.LEFT|wx.RIGHT, 5)
                    sizers[index].Add(sizer, 0, wx.EXPAND|wx.ALL, 0)
                else:
                    for index2, row in enumerate(d):
                        sizer = wx.BoxSizer(wx.HORIZONTAL)
                        for index3, v in enumerate(row[start:]):
                            t = wx.TextCtrl(self, -1, str(v), size=(width[index3], -1), name=names[index3]+str(index2)+str(index))
                            sizer.Add(t, 0, wx.LEFT|wx.RIGHT, 5)
                        sizers[index].Add(sizer, 0, wx.EXPAND|wx.ALL, 0)

    def GetData(self):
        for index, i in enumerate(self.data):
            if index == 0:
                names = self.TableANames
                start = 0
            else:
                names = self.TableBNames
                start = 2

            if len(i) != 0:
                for index2, j in enumerate(i):
                    if not isinstance(j, list):
                        if index != 0 and index2 < 2:
                            self.data[index][index2] = self.data[0][index2]
                        else:
                            obj = self.FindWindowByName(names[index2-start]+str(index))
                            text = obj.GetLineText(0)
                            self.data[index][index2] = text
                    else:
                        for index3, k in enumerate(j):
                            if index != 0 and index3 < 2:
                                self.data[index][index2][index3] = self.data[0][index3]
                            else:
                                obj = self.FindWindowByName(names[index3-start]+str(index2)+str(index))
                                text = obj.GetLineText(0)
                                self.data[index][index2][index3] = text


    def OnSave(self, event):

        self.GetData()
        Awaringemptindexes = [0, 1, 2, 3, 4, 5, 6]
        Bwaringemptindexes = [2, 3, 4]
        Awaringnumnames = [2, 3, 4, 5, 6]
        Bwaringnumnames = [3, 4]
        waringemptmessage = '数据不能为空！'
        waringnummessage = '填入数据必须为数字！'
        waringzeromessage = '填入数字不能为0！'
        for index, i in enumerate(self.data):
            for index2, j in enumerate(i):
                if index == 0:
                    wei = Awaringemptindexes
                    wnn = Awaringnumnames
                    tablename = self.TableANames
                else:
                    wei = Bwaringemptindexes
                    wnn = Bwaringnumnames
                    tablename = self.TableBNames

                if isinstance(j, list):
                    for index3, k in enumerate(j):
                        if index3 in wei and k == '':
                            wx.MessageDialog(self, '"' + tablename[index3-2] + '"' + waringemptmessage,
                            caption='警告',style=wx.OK|wx.ICON_WARNING).ShowModal()
                            return
                        
                        if index3 in wnn and not DataTool().isnum(k):
                            wx.MessageDialog(self, '"' + tablename[index3-2] + '"' + waringnummessage,
                            caption='警告',style=wx.OK|wx.ICON_WARNING).ShowModal()
                            return

                else:
                    index3 = index2
                    k = j
                
                    if index3 in wei and k == '':
                        wx.MessageDialog(self, '"' + tablename[index3] + '"' + waringemptmessage,
                        caption='警告',style=wx.OK|wx.ICON_WARNING).ShowModal()
                        return
                    
                    if index3 in wnn and not DataTool().isnum(k):
                        wx.MessageDialog(self, '"' + tablename[index3] + '"' + waringnummessage,
                        caption='警告',style=wx.OK|wx.ICON_WARNING).ShowModal()
                        return

        self.EndModal(retCode=1)

    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            
            return self.data
        else:
            return 5101

if __name__ == "__main__":
    import os
    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            # modal = DiaTable2add(self, 'baba').ShowModal()
            changdata = [['定额名称', '单位', '技工', '普工', '1', '2', '3', '']
                        , [['', '', '机械2', '单价2', '123'], ['', '', '机械3', '单价3', '123']]
                        , [['' ,  '' ,'仪表4', '1232', '22'], ['' ,  '' ,'仪表5', '123', '22']]]
            BASE_DIR = os.path.dirname(os.path.abspath(__file__))
            path=os.path.join(BASE_DIR, 'db')
            imagepath=os.path.join(BASE_DIR, 'icon')
            imagepath=os.path.join(imagepath, 'Check')
            imagepath=os.path.join(imagepath, 'Check Icon.png')
            path=os.path.join(path, 'quota.db')
            dia = ChangeData(self, 'haha', path=path, imagepath=imagepath, data=changdata)
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()